package com.example.cdtutils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 中电联data解密
 * @author Kent HAN
 * @date 2022-01-18
 */
public class Decrypt {
    public static String decrypt(String sSrc, String dataSecret, String dataSecretiv) {
        try {
            // 判断Key是否正确
            if (dataSecret == null) {
                return "Key为空null";
            }
            // 判断Key是否为16位
            if (dataSecret.length() != 16) {
                return "Key长度不是16位";
            }
            byte[] raw = dataSecret.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(dataSecretiv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "UTF-8");
                return originalString;
            } catch (Exception e) {
                //日志
                return null;
            }
        } catch (Exception ex) {
            //日志
            return null;
        }
    }
}
